package com.xudow.app.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.models.wor.WrongTopicWithInfo;
import com.xudow.app.R;
import com.xudow.app.ui.adapter.MistakeListAdapter;
import com.xudow.app.ui.task.ClazzMistakeRemoveTask;
import com.xudow.app.ui.task.ClazzMistakeTask;
import com.xudow.app.util.Maps;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 出题列表Fragment
 */
public class ClazzMistakeFragment extends BaseFragment implements MistakeListAdapter.ItemListener {

    private String studentId;
    private String subjectName;

    private MistakeListAdapter mistakeListAdapter;
    private ListView mistakeListView;

    private List<WrongTopicWithInfo> mistakes;

    private ClazzMistakeTask mistakeTask;
    private ClazzMistakeRemoveTask clazzMistakeRemoveTask;

    public static ClazzMistakeFragment newInstance(String studentId, String subjectName) {
        ClazzMistakeFragment fragment = new ClazzMistakeFragment();
        Bundle args = new Bundle();
        args.putString("studentId", studentId);
        args.putString("subjectName", subjectName);
        fragment.setArguments(args);
        return fragment;
    }

    public ClazzMistakeFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            studentId = getArguments().getString("studentId");
            subjectName = getArguments().getString("subjectName");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_clazz_mistake, container, false);

        mistakeListView = (ListView) view.findViewById(R.id.data_list);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (studentId != null) {
            loadMistakes();
        }
    }

    /**
     * 加载错题
     */
    private void loadMistakes() {
        HashMap<String, String> params = Maps.newHashMap();
        params.put("studentid", studentId);
        params.put("subjectname", subjectName);

        mistakeTask = new ClazzMistakeTask(getActivity(), mistakeHandler);
        mistakeTask.execute(params);
    }

    private Handler mistakeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (ClazzMistakeTask.SUCCESS == msg.what) {
                onMistakeSuccess(msg.getData());
            }
        }
    };

    private void onMistakeSuccess(Bundle data) {
        final WrongTopicWithInfo[] mistakeArr = (WrongTopicWithInfo[]) data.getSerializable("mistakes");

        if (null == mistakeArr || mistakeArr.length <= 0) {
            return;
        }

        mistakes = new ArrayList<WrongTopicWithInfo>();
        mistakes.addAll(Arrays.asList(mistakeArr));

        mistakeListAdapter = new MistakeListAdapter(getActivity(), android.R.layout.simple_list_item_1, mistakes);
        mistakeListAdapter.setItemListener(this);

        mistakeListView.setAdapter(mistakeListAdapter);
    }

    @Override
    public void onClick(int position) {
        Intent intent = new Intent(getActivity(), ClazzMistakeDetailActivity.class);
        intent.putExtra("studentId", "" + studentId);
        intent.putExtra("method", "show");
        intent.putExtra("wrongid", "" + mistakes.get(position).getId());
        intent.putExtra("subjectName", "" + mistakes.get(position).getSubjectName());

        startActivity(intent);
    }

    @Override
    public void onDelete(final int position) {
        String message = getString(R.string.delete_confirmation);
        AlertDialog dlg = new AlertDialog.Builder(getActivity())
                .setMessage(message)
                .setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //删除错题
                        showLodingDialog(getString(R.string.processing));

                        HashMap<String, String> params = Maps.newHashMap();
                        params.put("position", "" + position);
                        params.put("wrongid", "" + mistakes.get(position).getId());

                        clazzMistakeRemoveTask = new ClazzMistakeRemoveTask(getActivity(),
                                clazzMistakeRemoveTaskHandler);
                        clazzMistakeRemoveTask.execute(params);
                    }
                })
                .create();
        dlg.show();
    }

    /**
     * 删除错题Handler
     */
    private Handler clazzMistakeRemoveTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (ClazzMistakeRemoveTask.SUCCESS == msg.what) {
                int position = Integer.parseInt(msg.getData().getString("position"));

                mistakes.remove(position);
                mistakeListAdapter.notifyDataSetChanged();
            } else {
                String message = getString(R.string.delete_fail);
                Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public void onDestroy() {
        if (null != mistakeTask && !mistakeTask.isCancelled()) {
            mistakeTask.cancel(true);
            mistakeTask = null;
        }

        if (null != clazzMistakeRemoveTask && !clazzMistakeRemoveTask.isCancelled()) {
            clazzMistakeRemoveTask.cancel(true);
            clazzMistakeRemoveTask = null;
        }

        super.onDestroy();
    }
}
